﻿using System.Windows;
using System.Windows.Controls;
using Microsoft.Phone.Controls;
using System;
using System.Collections.Generic;
using System.Threading;
using VanGuideWP7.Helpers;
using System.Net;
using System.Windows.Navigation;
using VanGuideWP7.DataLoader;
using RedBit.WindowsPhone.ExternalApi.Twitter;
using GalaSoft.MvvmLight.Messaging;
using GalaSoft.MvvmLight.Threading;
using VanGuideWP7.Model;

namespace VanGuideWP7.View
{
    //TODO: Handle the case where the user hits the back button.

    /// <summary>
    /// Description for LoginPage.
    /// </summary>
    public partial class LoginPage : PhoneApplicationPage
    {
        /// <summary>
        /// Initializes a new instance of the LoginPage class.
        /// </summary>
        public LoginPage()
        {
            InitializeComponent();
            Messenger.Default.Register<TwitterMessages>(this, LoginSucess);
            this.Loaded += new RoutedEventHandler(TwitterAuth_Loaded);
        }

        void TwitterAuth_Loaded(object sender, RoutedEventArgs e)
        {
            TwitterHelper.Authenticate(this.webBrowser1);
        }

        private void LoginSucess(TwitterMessages msg)
        {
            if (msg == TwitterMessages.TwitterLoginSuccess)
            {
                DataUploaderProxy.Login();
                
                DispatcherHelper.UIDispatcher.BeginInvoke(() =>
                    {
                        Messenger.Default.Send(true, MessageTokens.TwitterLoginValueChanged);
                        NavigationService.GoBack();
                    });
            }
        }
    }
}